//
//  ServiceManager.m
//  Common
//
//  Created by liurongming on 16/4/12.
//  Copyright © 2016年 IT.Bear. All rights reserved.
//

#import "ServiceManager.h"
#import "OpenUDID.h"
#import "SessionManager.h"
#import "ZipArchive.h"
#import "FFTools.h"
#import <AdSupport/AdSupport.h>

#import "MBManager.h"

//VC，移至时可直接去掉
#import "FFWebViewController.h"

@implementation ServiceManager

/**
 * post请求
 * @param strUrl 服务器地址
 * @param dicRequest 请求数据
 * @param dictResponse 响应数据
 */
+ (void)postTrans:(NSString *)strUrl withRequest:(NSDictionary*)dicRequest success:(void (^)(NSDictionary* dictResponse, BOOL result)) success failure:(void(^)(NSError *error)) failure{
   
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    
    NSString *method = strUrl;
    
    NSArray *paramsValue = [dicRequest allValues];
    NSArray *paramsKey = [dicRequest allKeys];
    NSMutableArray *paramsArr = [NSMutableArray array];
    for (int i = 0; i<paramsKey.count; i++) {
        NSString *paramstr = [NSString stringWithFormat:@"%@:%@",paramsKey[i],dicRequest[paramsKey[i]]];
        [paramsArr addObject:paramstr];
    }
    NSArray* arraySorted = [paramsArr sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
    NSString *appendString = @"";
    //将参数升序排列 拼接后加上method 和 time 组成sign原始串
    for (int i = 0; i<arraySorted.count; i++) {
        if (i == 0) {
            appendString = arraySorted[0];
        }else{
            appendString = [appendString stringByAppendingFormat:[NSString stringWithFormat:@",%@",arraySorted[i]]];
        }
    }
    
    appendString = [appendString stringByAppendingString:[NSString stringWithFormat:@",method:%@",method]];
    
    NSString * timesp = [FFTools getTimesp];
    appendString = [appendString stringByAppendingString:[NSString stringWithFormat:@",time:%@",timesp]];
    NSString *sign = @"";
    if (appendString.length > 0) {
        //sign md5加密
        sign = [appendString md5String];
        sign = sign.lowercaseString;
    }else{
        NSLog(@"签名串错误");
    }
    
    //系统参数
    NSMutableDictionary *systemDic = [NSMutableDictionary dictionary];
    [systemDic setValue:APPOUTVERSION forKey:@"ver"];
    [systemDic setValue:sign forKey:@"sign"];
    [systemDic setValue:timesp forKey:@"time"];
    
    //最后的上传格式
    [params setValue:method forKey:@"method"];
    [params setValue:dicRequest forKey:@"params"];
    [params setValue:systemDic forKey:@"system"];
    
    NSDictionary *infoDict = [[NSBundle mainBundle] infoDictionary];
    NSString *nowVersion = [infoDict objectForKey:@"CFBundleShortVersionString"];
    
    NSString *udid = [OpenUDID value];

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setCachePolicy:NSURLRequestReloadIgnoringCacheData];
    [request setTimeoutInterval: 15];
    [request setHTTPShouldHandleCookies:TRUE];
    [request setValue:@"ios" forHTTPHeaderField:@"clientType"];
    [request setValue:udid forHTTPHeaderField:@"imeiNo"];
    //IDFA
    NSString
    *idfa = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    [request setValue:idfa forHTTPHeaderField:@"idfa"];
    [request setValue:nowVersion forHTTPHeaderField:@"clientVersion"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    //token
    NSString *token = [[NSUserDefaults standardUserDefaults] valueForKey:@"token"];
    [request setValue:token forHTTPHeaderField:@"accessToken"];
    
    if ([strUrl hasPrefix:@"http"]) {
        [request setURL:[NSURL URLWithString:strUrl]];
    }
    else{
        [request setURL:[NSURL URLWithString:MAIN_SERVER(strUrl)]];
    }
    
    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:[dicRequest JSONData]];

    LOG(@"URL ==>%@",MAIN_SERVER(strUrl));
    LOG(@"Parameter ==>%@",dicRequest);
    
    [MBManager showGloomy:NO];
    [MBManager showLoading];
    AFHTTPSessionManager *manager = [HTTPSessionManager sharedURLSession];
//    manager.requestSerializer.timeoutInterval = 15;
//    AFURLSessionManager *manager = [FFSessionManager sharedURLSession] ;
    [[manager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        
        [MBManager hideAlert];
        
        NSHTTPURLResponse *HTTPResponse = (NSHTTPURLResponse *)response;
        NSInteger statusCode = [HTTPResponse statusCode];
        NSLog(@"STATUS Code :%ld ", (long)statusCode);
        
       
        if (!error) {
            NSDictionary *responseDic ;
            if ([responseObject isKindOfClass:[NSDictionary class]]) {
                responseDic = responseObject;//[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            }else if ([responseObject isKindOfClass:[NSData class]]) {
                responseDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            }
            if ([responseDic isKindOfClass:[NSDictionary class]]) {
                NSLog(@"data:%@",responseDic);
                //存储服务器时间
                if (responseDic[@"timestamp"]) {
                    NSString *time = [NSString stringWithFormat:@"%@",responseDic[@"timestamp"]];
//                    [[FFConfiguration sharedInstance] getTimeDifferenceWithServerTime:time];
                }
                NSInteger status = [responseDic[@"status"] integerValue];
                //登录失败，重新登录
                if (status == -3 ) {
                    [self goLogin];
                    success(responseDic,NO);
                }
                else if (status == 0) {
                    success(responseDic,YES);
                }else{
                    success(responseDic,NO);
                }
            }
        } else {
            LOG(@"Error: %@, %@, %@", error, response, responseObject);
            failure(error);
        }
    }] resume];
}

/**
 * 发送网络请求GET
 * @param strUrl 服务器地址
 * @param dicRequest 请求数据
 * @param dictResponse 响应数据
 */
+ (void)getTrans:(NSString *)strUrl withRequest:(NSDictionary*)dicRequest success:(void (^)(NSDictionary* dictResponse)) success failure:(void(^)(NSError *error)) failure
{
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setCachePolicy:NSURLRequestReloadIgnoringCacheData];
    [request setTimeoutInterval: 15];
    [request setHTTPShouldHandleCookies:TRUE];
    [request setValue:@"IOS" forHTTPHeaderField:@"PLATFORM"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    //token
    NSString *token = [[NSUserDefaults standardUserDefaults] valueForKey:@"token"];
    [request setValue:token forHTTPHeaderField:@"accessToken"];
    
    if ([strUrl hasPrefix:@"http"]) {
        [request setURL:[NSURL URLWithString:strUrl]];
    }
    else{
        [request setURL:[NSURL URLWithString:MAIN_SERVER(strUrl)]];
    }
    [request setHTTPMethod:@"GET"];
    [request setHTTPBody:[dicRequest JSONData]];

    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [[manager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        
        NSHTTPURLResponse *HTTPResponse = (NSHTTPURLResponse *)response;
        NSInteger statusCode = [HTTPResponse statusCode];
        NSLog(@"----------------------------------------------------");
        NSLog(@"status code :%ld ", (long)statusCode);
        
        if (!error) {
            NSDictionary *responseDic ;
            if (responseObject) {
                responseDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            }
            if ([responseDic isKindOfClass:[NSDictionary class]]) {
                LOG(@"data:%@",responseDic);
                success(responseDic);
            }
        } else {
            LOG(@"Error: %@, %@, %@", error, response, responseObject);
            failure(error);
        }
    }] resume];
}

+ (void)uploadImage:(UIImage *)image toURL:(NSString *)url withName:(NSString *)uploadName params:(NSDictionary *)dic success:(void(^)(NSDictionary* dictResponse, BOOL result))success failure:(void (^)(id error))failure
{

    url = MAIN_SERVER(url);
    LOG(@"url:%@",url);
    if (isIOS8)
    {
        
        AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] init];
        
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        [manager POST:url parameters:dic constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
            NSData *data = UIImageJPEGRepresentation(image, 0.3);
//            long long size = data.length/1000;
            [formData appendPartWithFileData:data name:uploadName fileName:@"img.jpg" mimeType:@"image/jpg"];
        } progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if (success) {
                NSDictionary *responseDic ;
                if (responseObject) {
                    responseDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
                }
                if ([responseDic isKindOfClass:[NSDictionary class]]) {
                    LOG(@"data:%@", responseDic);
                    
                    //存储服务器时间
                    if (responseDic[@"timestamp"]) {
                        NSString *time = [NSString stringWithFormat:@"%@",responseDic[@"timestamp"]];
//                        [[FFConfiguration sharedInstance] getTimeDifferenceWithServerTime:time];
                    }
                    NSInteger status = [responseDic[@"status"] integerValue];
                    //登录失败，重新登录
                    if (status == -3 ) {
                        [self goLogin];
                        success(responseDic,NO);
                    }
                    else if (status == 0) {
                        success(responseDic,YES);
                    }else{
                        success(responseDic,NO);
                    }
                }
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            if (failure) {
                failure(error);
            }
        }];
    }
    else
    {
        NSString *tempFilename = [NSString stringWithFormat:@"%f",[NSDate timeIntervalSinceReferenceDate]];
        NSURL *temFileUrl = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingPathComponent:tempFilename]];
        NSMutableURLRequest *multipartRequest = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:url parameters:dic constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
            NSData *data = UIImagePNGRepresentation(image);
            [formData appendPartWithFileData:data name:uploadName fileName:@"img.png" mimeType:@"image/png"];
        } error:nil];
        
        [[AFHTTPRequestSerializer serializer] requestWithMultipartFormRequest:multipartRequest writingStreamContentsToFile:temFileUrl completionHandler:^(NSError * _Nullable error) {
            AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
            manager.responseSerializer = [AFHTTPRequestSerializer serializer];
            NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:multipartRequest fromFile:temFileUrl progress:nil completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
                if (error) {
                    if (failure) {
                        failure(error);
                    }else{
                        NSDictionary *responseDic ;
                        if (responseObject) {
                            responseDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
                        }
                        if ([responseDic isKindOfClass:[NSDictionary class]]) {
                            LOG(@"data:%@",responseDic);
                            
                            //存储服务器时间
                            if (responseDic[@"timestamp"]) {
                                NSString *time = [NSString stringWithFormat:@"%@",responseDic[@"timestamp"]];
//                                [[FFConfiguration sharedInstance] getTimeDifferenceWithServerTime:time];
                            }
                            NSInteger status = [responseDic[@"status"] integerValue];
                            //登录失败，重新登录
                            if (status == -3 ) {
                                [self goLogin];
                                success(responseDic,NO);
                            }
                            else if (status == 0) {
                                success(responseDic,YES);
                            }else{
                                success(responseDic,NO);
                            }
                        }

                    }
                }
            }];
            [uploadTask resume];
        }];
        
    }
    
}

+ (void)uploadImages:(NSArray *)imageArray toURL:(NSString *)url withName:(NSString *)uploadName params:(NSDictionary *)dic success:(void(^)(id responseObject))success failure:(void (^)(id error))failure
{
    __block NSError *error = nil;
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer]multipartFormRequestWithMethod:@"POST" URLString:url parameters:dic constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        if (imageArray.count > 0) {
            for (int i = 0; i < imageArray.count; i++) {
                NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
                formatter.dateFormat = @"yyyyMMddHHmmss";
                NSString *str = [formatter stringFromDate:[NSDate date]];
                NSString *fileName = [NSString stringWithFormat:@"%@.jpg", str];
                
                [formData appendPartWithFileData:UIImageJPEGRepresentation(imageArray[i],0.5)
                                            name:[NSString stringWithFormat:@"image%d",i+1]
                                        fileName:fileName
                                        mimeType:@"image/jpeg"];
            }
            
        }
        
    } error:nil];
    
    NSString *tempFilename = [NSString stringWithFormat:@"%f",[NSDate timeIntervalSinceReferenceDate]];
    NSURL *temFileUrl = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingPathComponent:tempFilename]];
    [[AFHTTPRequestSerializer serializer] requestWithMultipartFormRequest:request writingStreamContentsToFile:tempFilename completionHandler:^(NSError * _Nullable error) {
        AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
        manager.responseSerializer = [AFHTTPRequestSerializer serializer];
        NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:temFileUrl progress:nil completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
            if (error) {
                if (failure) {
                    failure(error);
                }else{
                    if (success) {
                        success(responseObject);
                    }
                }
            }
        }];
        [uploadTask resume];
    }];
}

+ (void)uploadFileWithUrl:(NSString *)url success:(void(^)(NSDictionary* dictResponse, BOOL result))success failure:(void (^)(id error))failure
{
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    //创建AFN的manager对象
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:configuration];
    //构造URL对象
    NSURL *fileUrl = [NSURL URLWithString:url];
    //构造request对象
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:fileUrl];
    //使用系统类创建downLoad Task对象
    NSURLSessionDownloadTask *task = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        LOG(@"主题下载进度：%@", downloadProgress);//下载进度
        
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        //返回下载到哪里(返回值是一个路径)
        //拼接存放路径
        NSURL *pathURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:YES error:nil];
        return [pathURL URLByAppendingPathComponent:[response suggestedFilename]];
        
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        //下载完成走这个block
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
        NSString *path = [paths lastObject];
        NSFileManager *fileManager = [NSFileManager defaultManager];
        //解压缩文件路径
        NSString *directryPath = [path stringByAppendingPathComponent:@"themeImages"];
        if (!error)
        {
            //如果请求没有错误(请求成功), 则打印地址
            ZipArchive* zip= [[ZipArchive alloc]init];
            //在内存中解压缩文件,固定路径
            NSString *unzipPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"theme.zip"];
            if([zip UnzipOpenFile:unzipPath]){
                //2.将解压缩的内容写到缓存目录中
                BOOL isExist = [fileManager fileExistsAtPath:directryPath];
                if (!isExist) {
                    [fileManager createDirectoryAtPath:directryPath withIntermediateDirectories:YES attributes:nil error:nil];
                }else{
                    [fileManager removeItemAtPath:directryPath error:nil];
                    [fileManager createDirectoryAtPath:directryPath withIntermediateDirectories:YES attributes:nil error:nil];
                }
                BOOL ret = [zip UnzipFileTo:directryPath overWrite:YES];
                
                if(NO == ret) {
                    [zip UnzipCloseFile];
                    [fileManager removeItemAtPath:unzipPath error:nil];
                    [fileManager removeItemAtPath:directryPath error:nil];
                    success(nil,NO);
                }else{
                    [fileManager removeItemAtPath:unzipPath error:nil];
                    success(filePath,YES);
                }
                NSLog(@"%@", filePath);
            }else{
                //解压失败
                [zip UnzipCloseFile];
                success(nil,NO);
                [fileManager removeItemAtPath:directryPath error:nil];
                [fileManager removeItemAtPath:unzipPath error:nil];
            }
        }else{
            //删除压缩包
            NSString *unzipPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"theme.zip"];
            [fileManager removeItemAtPath:unzipPath error:nil];
            [fileManager removeItemAtPath:directryPath error:nil];
            success(nil,NO);
        }
    }];
    //开始请求
    [task resume];
}

+ (void)goLogin{
    FFWebViewController *webVC = (FFWebViewController *)[UIApplication sharedApplication].keyWindow.rootViewController;
    [webVC goLogin];
}

@end
